<?php

$key = include "./lib/key.php";

function rand_char($len = 32) {
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;
    for ($i = 0; $i < $len; $i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}



$param = $_POST;
$aesKey = $param["aesKey"];
$aesIv = $param["aesIv"];
$aesData = $param["aesData"];

// 解密请求的AES的key和iv
$rsa = new \lib\RSA();
$aesKey = $rsa->decrypt($aesKey,$key["serverPrivateKey"]);
$aesIv = $rsa->decrypt($aesIv,$key["serverPrivateKey"]);

// 解密请求的AES密文
$aes = new \lib\AES($aesKey, $aesIv);
$aesDecrypted = $aes->decrypt($aesData);

$responseAESKey = rand_char(16);
$responseAESIv = rand_char(16);
$responseData = "客户端数据为：{$aesDecrypted}";
$aes = new \lib\AES($responseAESKey, $responseAESIv);
$responseAESData = $aes->encrypt($responseData);
$responseAESKeyRSASign = $rsa->sign($responseAESKey,$key["serverPrivateKey"]);
$responseAESIvRSASign = $rsa->sign($responseAESIv,$key["serverPrivateKey"]);

$res = [
    "aesKey"=>$responseAESKey,
    "aesKeyRsaSign"=>$responseAESKeyRSASign,
    "aesIv"=>$responseAESIv,
    "aesIvRsaSign"=>$responseAESIvRSASign,
    "aesData"=>$responseAESData,
];

response($res);